const axios = require('axios')
const { stringify } = require('qs')

const { responsParser } = require('../utils/parser')
const { success, info, warn, clg } = require('../utils/output')

const submitRequest = async (submitUrl, id, userinfo) => {
  info('尝试提交申请...')
  const params = { id }
  const responsMap = new Map([
    ['提交成功', true],
    ['已有申请尚未审批完成', false]
  ])

  // 解构参数 作为提交申请的参数
  const {
    type,
    cause,
    destination,
    outProvince,
    transport,
    leaveTime,
    returnTime
  } = userinfo

  info('要提交的参数如下：')
  clg({
    type,
    cause,
    destination,
    outProvince,
    transport,
    leaveTime,
    returnTime
  })

  const { data } = await axios.post(
    submitUrl,
    stringify({
      lxlx: type,
      lxsy: cause,
      lxmdd: destination,
      outp: +outProvince,
      jtfs: transport,
      lxsk: leaveTime,
      fxsk: returnTime,
      Submit: '提交',
      action: 'add'
    }),
    { params }
  )

  // 解析页面返回结果
  const msg = responsParser(data)
  responsMap.get(msg) ? success(msg) : warn('提交失败，原因是：' + msg)
}

module.exports = submitRequest